/**
 * @param {number[][]} mat
 * @param {number} r
 * @param {number} c
 * @return {number[][]}
 */
export var matrixReshape = function (mat, r, c) {
  const [r0, c0] = [mat.length, mat[0].length]
  if (r0 === r && c0 === c) return mat
  if (r * c !== r0 * c0) return mat
  // 打平数组
  // const flat = mat.reduce((a, b) => a.concat(b), [])
  const flat = mat.flat(Infinity) // ES10打平数组方法
  const ans = new Array(r).fill(0).map(() => new Array(c).fill(0))
  let rPoint = 0
  let cPoint = 0
  for (let i = 0; i < flat.length; i++) {
    ans[rPoint][cPoint] = flat[i]
    cPoint++
    if (cPoint === c) {
      cPoint = 0
      rPoint++
    }
  }
  return ans
}

export const matrixReshape2 = function (mat, r, c) {
  const [r0, c0] = [mat.length, mat[0].length]
  if (r * c !== r0 * c0) return mat
  // 打平数组
  const flat = mat.flat(Infinity) // ES10打平数组方法
  const ans = []
  for (let i = 0; i < r; i++) {
    const rowItem = []
    for (let j = 0; j < c; j++) {
      rowItem.push(flat[i * c + j])
      // rowItem.push(flat.shift()) // shift()似乎会慢一点
    }
    ans.push(rowItem)
  }
  return ans
}
